<template>
  <!-- 新增弹框 -->
  <el-dialog title="编辑弹层" :visible="showDialog" @close="closeDialog" @open="fetchDetail">
    <!-- 表单内容 -->
    <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="roleForm.description" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <template>
      <el-row slot="footer" type="flex" justify="center">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" @click="confirmAdd">确定</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addRole, getRoleDetail, updateRole } from '@/api/setting'
export default {
  name: 'AddRole',
  props: {
    showDialog: {
      type: Boolean
    },
    couId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      roleDialogVisible: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.eddRole()
  },
  methods: {
    closeDialog() {
      this.$emit('close-dialog')
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    confirmAdd() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          if (this.roleForm.id) {
            await updateRole(this.roleForm)
          } else {
            await addRole(this.roleForm)
          }

          this.$emit('updata-List')
          this.$refs.roleForm.resetFields()
          this.$message.success('添加成功')
          this.closeDialog()
        }
      })
    },
    async eddRole() {
      const res = await getRoleDetail(this.couId)
      this.roleForm = res
    },
    fetchDetail() {
      if (!this.roleForm.id) {
        this.eddRole()
      }
    }

  }

}
</script>
